﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Siser.Web.Models;

namespace Siser.Web.Authorization
{
    public class RequiresAuthorization : AuthorizeAttribute
    {
        private SiserEntities db = new SiserEntities();

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("AuthorizeFilterAttribute");

            var result = from u in db.Usuarios
                         join r in db.Roles on u.RolId equals r.Id
                         join rf in db.RolesFuncionalidades on r.Id equals rf.RolId
                         join f in db.Funcionalidades on rf.FuncionalidadId equals f.Id
                         where u.Nombre == HttpContext.Current.User.Identity.Name
                         select f;

            string actionName = filterContext.ActionDescriptor.ActionName;
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            if (result.Count() == 0 || result.FirstOrDefault(f => f.Accion == actionName && f.Controlador == controllerName) == null)
                if (filterContext.HttpContext.Request.IsAuthenticated)
                    filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult(403);
                else
                    filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}